package controllers

import (
	"chess/api/models"
	"encoding/json"
	"fmt"
	"net/http"
	"os/exec"

	"github.com/gorilla/websocket"

	"github.com/astaxie/beego"
)

var WsManager map[string]*models.WS

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.TplName = "index.html"
}

func (c *MainController) A更新() {
	cmd := exec.Command("git", "pull")
	err := cmd.Run()
	if err != nil {
		c.Fail(1, err)
		return
	}
	c.Success("更新成功")
}

func (c *MainController) Ws() {
	guid := c.GetString("guid") // 识别浏览器
	conn, err := websocket.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(c.Ctx.ResponseWriter, "Not a websocket handshake", 400)
		return
	}

	if WsManager == nil {
		WsManager = make(map[string]*models.WS)
	}
	WsManager[guid] = &models.WS{Conn: conn, Guid: guid}

	defer conn.Close()

	c.Success("success")

	for {
		mt, message, err := conn.ReadMessage()
		if err != nil {
			beego.Error("read:", err)
			break
		}
		var 数据 models.M数据
		err = json.Unmarshal(message, &数据)
		if err != nil {
			beego.Error("json unmarshal:", err)
			break
		}
		beego.Info("recv:", string(message))
		switch 数据.F类型 {
		case "走棋":
			走棋(数据.OldX, 数据.OldY, 数据.NewX, 数据.NewY)
			最近走棋 = 数据
		case "悔棋":
			悔棋()
		case "重开":
			走棋记录 = make([][][]string, 0)
			开始(起始布局)
		case "设置阵营":
			WsManager[guid].F阵营 = 数据.F阵营
		}

		m := map[string]interface{}{}
		m["棋子坐标"] = 棋子坐标
		m["棋子映射"] = 棋子映射
		m["最近走棋"] = 最近走棋
		data, err := json.Marshal(m)
		if err != nil {
			beego.Error("json marshal:", err)
			break
		}
		for _, v := range WsManager {
			err = v.Conn.WriteMessage(mt, data)
			if err != nil {
				beego.Error("write:", err)
			}
		}
	}
}

func (c *MainController) Fail(返回码 int, 数据 interface{}) {
	var msg string
	switch 数据.(type) {
	case string:
		msg = 数据.(string)
	default:
		msg = fmt.Sprint(数据)
	}
	c.Data["json"] = map[string]interface{}{"返回码": 返回码, "数据": msg}
	c.ServeJSON()
}

func (c *MainController) Success(数据 interface{}) {
	c.Data["json"] = map[string]interface{}{"返回码": 0, "数据": 数据}
	c.ServeJSON()
}
